import Footer from '@/components/Footer';
import RightContent from '@/components/RightContent';
import { BookOutlined, LinkOutlined } from '@ant-design/icons';
import type { Settings as LayoutSettings } from '@ant-design/pro-components';
import { PageLoading, SettingDrawer } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from 'umi';
import { history, Link } from 'umi';
import defaultSettings from '../config/defaultSettings';
import { currentUser as queryCurrentUser } from './services/ant-design-pro/api';
import { getUserInfo, isLogin } from "@/utils/format";
import './global.less'
import moment from 'moment';
import 'moment/locale/zh-cn';
import locale from 'antd/lib/locale/zh_CN';
import routes_xk from "../config/routes_xk";
import routes_school from "../config/routes_school";
import routes_province from "../config/routes_province";
import React from "react";
import { useRef } from 'react';
import { useModel } from "umi";
import { Typography } from "antd";
import routes_subject_detail from "../config/routes_subject_detail";
import MenuLogo from "../config/logos/MenuLogo";
import { AllSchools } from "@/services/DashApi";
import { SubjectsOfSchool, UserCacheApi } from "@/services/Province/Dashboard";
import Cookies from "js-cookie";

const isDev = process.env.NODE_ENV === 'development';
const loginPath = '/user/login';

/** 获取用户信息比较慢的时候会展示一个 loading */
// export const initialStateConfig = {
//   loading: <PageLoading />,
// };

/**
 * @see  https://umijs.org/zh-CN/plugins/plugin-initial-state
 * */
export async function getInitialState(): Promise<{
  settings?: Partial<LayoutSettings>;
  currentUser?: API.CurrentUser;
  loading?: boolean;
  fetchUserInfo?: () => Promise<API.CurrentUser | undefined>;
}> {
  // const fetchUserInfo = async () => {
  //   try {
  //     const msg = await queryCurrentUser();
  //     return msg.data;
  //   } catch (error) {
  //     history.push(loginPath);
  //   }
  //   return undefined;
  // };
  // // 如果不是登录页面，执行
  // if (history.location.pathname !== loginPath) {
  //   const currentUser = await fetchUserInfo();
  //   return {
  //     fetchUserInfo,
  //     currentUser,
  //     settings: defaultSettings,
  //   };
  // }
  // return {
  //   fetchUserInfo,
  //   settings: defaultSettings,
  // };
}

// ProLayout 支持的api https://procomponents.ant.design/components/layout
export const layout: RunTimeLayoutConfig = ({ initialState, setInitialState }) => {
  return {
    title: "江西省双一流建设信息管理平台",
    logo: false,
    onMenuHeaderClick: () => {
      console.log("@onMenuHeaderClick")
      window.location.href = "/"
    },
    defaultCollapsed: false,
    disableMobile: true,
    breakpoint: false,
    collapsed: false,
    collapsedButtonRender: undefined,
    links: [],
    menu: {
      request: async () => {
        const userInfo = getUserInfo()
        if (userInfo.role === "省厅管理员") {
          // 更换菜单为5个监测点
          const url = history.location.pathname
          if (url.indexOf('/province/subject_detail/') === 0) {
            const urlArr = url.split('/')
            const school = urlArr[urlArr.length - 1]
            const subject = urlArr[urlArr.length - 2]
            for (let i = 0; i < routes_subject_detail.length; i++) {
              routes_subject_detail[i].path += '/' + subject + '/' + school
              routes_subject_detail[i].key += '/' + subject + '/' + school
              routes_subject_detail[i].openKeys += '/' + subject + '/' + school
              routes_subject_detail[i].name = <Link to={routes_subject_detail[i].path} style={{ display: "block", color: "black" }}>{routes_subject_detail[i].name}</Link>
              if (routes_subject_detail[i].routes && routes_subject_detail[i].routes.length > 0) {
                for (let j = 0; j < routes_subject_detail[i].routes.length; j++) {
                  routes_subject_detail[i].routes[j].path += '/' + subject + '/' + school
                }
              }
            }
            console.log("@routes_subject_detail", routes_subject_detail)
            console.log("@routes_subject_detail", routes_subject_detail.length)
            console.log("@routes_subject_detail", routes_subject_detail[0].name.props)
            return routes_subject_detail
          }

          // 正常菜单
          return routes_province
        } else if (userInfo.role === "学科填报用户") {
          return routes_xk
        } else {
          return routes_school
        }
      },
    },
    menuItemRender: (item, dom) => {
      // 添加学校Logo
      if (MenuLogo[item.itemPath] !== undefined) {
        return <Link to={item.itemPath}>
          <img
            src={MenuLogo[item.itemPath]}
            style={{ width: 30, height: 30, marginBottom: 5 }}
          /> {dom}
        </Link>
      }
      return <Link to={item.itemPath}>{dom}</Link>
    },
    rightContentRender: () => <RightContent />,
    disableContentMargin: false,
    waterMarkProps: {
      content: initialState?.currentUser?.name,
    },
    footerRender: () => <Footer />,
    route: {
      path: '/',
      routes: routes_province,
    },
    onPageChange: () => {
      const { location } = history;
      // 如果没有登录，重定向到 login
      if (location.pathname !== '/user/login' && !location.pathname.includes('auth2Login')) {
        UserCacheApi().then(res => {
          console.log(res)
          if (res.status === 1) {
            Cookies.remove('userInfo')
            history.push('/user/login')
          }
        })
      }
    },
    // links: isDev
    //   ? [
    //       <Link key="openapi" to="/umi/plugin/openapi" target="_blank">
    //         <LinkOutlined />
    //         <span>OpenAPI 文档</span>
    //       </Link>,
    //       <Link to="/~docs" key="docs">
    //         <BookOutlined />
    //         <span>业务组件文档</span>
    //       </Link>,
    //     ]
    //   : [],
    menuHeaderRender: undefined,
    // 自定义 403 页面
    // unAccessible: <div>unAccessible</div>,
    // 增加一个 loading 的状态
    // childrenRender: (children, props) => {
    //   // if (initialState?.loading) return <PageLoading />;
    //   return (
    //     <>
    //       {children}
    //       {!props.location?.pathname?.includes('/login') && (
    //         <SettingDrawer
    //           disableUrlParams
    //           enableDarkTheme
    //           settings={initialState?.settings}
    //           onSettingChange={(settings) => {
    //             setInitialState((preInitialState) => ({
    //               ...preInitialState,
    //               settings,
    //             }));
    //           }}
    //         />
    //       )}
    //     </>
    //   );
    // },
    // ...initialState?.settings,
  };
};

// 覆盖 render，用于检测用户是否登录 api https://v3.umijs.org/zh-CN/docs/runtime-config#renderoldrender-function
export function render(oldRender) {
  console.log('@用户是否登录')
  console.log("location.pathname " + location.pathname)
  if (location.pathname !== '/user/login' && !location.pathname.includes('auth2Login') && !isLogin()) {
    history.push('/user/login')
  }
  oldRender()
}


// export function rootContainer(container) {
//   console.log("@rootContainer", container)
//   return React.createElement(container)
//   // return React.createElement(ThemeProvider, null, container);
// }
